import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { ContractManageAPI } from '../common/type';
import { UpdateTableCommon } from './UpdateTableCommon';
import { ConractControllerContext, IContractsActionEnum } from '../common';
import { copyTemplateService, updateTempDataGrid } from '../services';
import { updateTempColumns } from '../mconfig';
import { onCloseModalCommon } from '@/utils';
import { Spin, message } from 'antd';
import { OpenTemplateInfoModal } from './OpenTemplateInfoModal';

export const OpenContractTempModal: React.FC<ContractManageAPI.IOpenContractTempModal> = ({ onClose, contractFormName }) => {
  /**弹框的ref*/
  const tempDataModalRef: Ref<IOneModalRef> = useRef(null);

  /** 获取上下文 */
  const { curRes, contractTempRow, styleFixCls, contractDispatch, contractForm } = useContext(ConractControllerContext);

  /** 获取列表 */
  const { data, params, loading, pagination, searchList, getManageData } = updateTempDataGrid(curRes, contractFormName?.getFieldValue('businessType'));

  /** 保存选中数据 */
  const [selectTempInfo, setSelectTempInfo] = useState<Record<string, any>>({});

  /** 是否打开使用说明 */
  const [openTempExplain, setOpenTempExplain] = useState<Record<string, any>>({
    isOpen: false,
    checkInfo: {},
  });

  /** 搜索 */
  const onSearch = (payload: Record<string, any>) => {
    /** 将合同基本信息表单中 合同类型参数带入 */
    getManageData({ ...payload, businessType: contractForm?.getFieldValue('businessType') });
  };

  /** 重置 */
  const onReset = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo: any) => {
    setSelectTempInfo(selectInfo);
  };

  /** 分页change 方法 */
  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /** 初始化 */
  useEffect(() => {
    if (!contractFormName?.getFieldValue('templateID')) {
      return setSelectTempInfo([]);
    }

    if (contractTempRow && JSON.stringify(contractTempRow) != '{}') {
      setSelectTempInfo(contractTempRow);
    }
  }, [contractTempRow]);

  /** 复制范本路径接口 */
  const copyCallback = (res: any) => {
    if (res && res?.msgFlag) {
      contractFormName?.setFieldsValue({
        templateURL: res?.obj?.templateURL,
        contractURL: res?.obj?.contractURL,
        templateType: selectTempInfo?.templateType,
        templateID: selectTempInfo?.id,
      });
      onCloseModalCommon(tempDataModalRef);
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入复制路径接口 */
  const { copyTemplateLoading, copyTemplateRun } = copyTemplateService(copyCallback);

  /** 保存 */
  const onSave = () => {
    if (selectTempInfo && JSON.stringify(selectTempInfo) != '{}') {
      copyTemplateRun({
        templateID: selectTempInfo?.id,
        templateURL: selectTempInfo?.templateURL,
      });
      contractDispatch({
        type: IContractsActionEnum.SELECT_COUNTERTEMPLA,
        payload: selectTempInfo,
      });
    } else {
      message.warning('请选择合同范本！');
    }
  };

  /** 打开使用说明 */
  const openExolain = (resObj: Record<string, any>) => {
    setOpenTempExplain({
      isOpen: true,
      checkInfo: resObj,
    });
  };

  /** 处理返回表格配置 */
  const cloumnMemo = useMemo(() => {
    return updateTempColumns(openExolain);
  }, [openTempExplain]);

  return (
    <OneModal
      open={true}
      getContainer={false}
      ref={tempDataModalRef}
      title={'选择合同范本'}
      onCancel={onClose}
      width={document.body.clientWidth * 0.6}
      bodyStyle={{
        height: document.body.clientHeight * 0.55,
        padding: 0,
      }}
      onOk={onSave}
    >
      <Spin spinning={copyTemplateLoading}>
        <UpdateTableCommon
          styleFixCls={styleFixCls}
          searchProps={{
            searchList,
            onReset,
            onSearch,
          }}
          selectTablePorps={{
            onSelectTable,
            selectRowObjList: selectTempInfo ? [selectTempInfo] : [],
          }}
          tableProps={{
            columns: cloumnMemo,
            loading,
            rowKey: 'id',
            dataSource: data?.rows,
            pagination,
            onPageChange,
          }}
        />
      </Spin>

      {/* 打开使用说明 */}
      {openTempExplain?.isOpen && (
        <OpenTemplateInfoModal
          onClose={() => {
            setOpenTempExplain({
              isOpen: false,
              checkInfo: {},
            });
          }}
          checkInfo={openTempExplain?.checkInfo}
        />
      )}
    </OneModal>
  );
};
